package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.caucho.hessian.server.HessianServlet;

public class BasicService extends HessianServlet implements BasicAPI {
	private String[] tab = { "Hello, world", "pepe", "sisi", "nana", "fofo" };
	private int n = 0;
	private File uploadDir = new File("upload");
	private static final String SEPARATOR = ".part.";

	public BasicService() {
		uploadDir.mkdirs();
	}

	public String hello() {
		String result = tab[n];
		n++;
		n %= tab.length;
		return result;
	}

	@Override
	public boolean upload(String fileName, int n, byte[] tab) {
		File file = new File(uploadDir, fileName + SEPARATOR + n);
		FileOutputStream os;
		try {
			os = new FileOutputStream(file);
			os.write(tab);
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean uploadFinish(final String fileName) {
		Runnable task = new Runnable() {
			@Override
			public void run() {
				try {
					File outFile = new File(uploadDir, fileName);
					FileOutputStream os = new FileOutputStream(outFile);
					for (int i = 0;; i++) {
						File file = new File(uploadDir, fileName + SEPARATOR
								+ i);
						if (!file.isFile())
							break;
						addContent(os, file);
						file.delete();
					}
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(task).start();
		return true;
	}

	private void addContent(FileOutputStream os, File file) throws IOException {
		int len = (int) file.length();
		byte[] tab = new byte[len];
		FileInputStream is = new FileInputStream(file);
		is.read(tab);
		os.write(tab);
		is.close();
	}
}
